package com.jmu.edu.IMApplication.fragment;

import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.adapter.ReviseCustomTextItemAdapter;
import com.jmu.edu.IMApplication.bean.GestureAndFaceResult;
import com.jmu.edu.IMApplication.myview.EditDialog;
import com.jmu.edu.IMApplication.net.bean.UserIdentify;
import com.jmu.edu.IMApplication.utils.HttpUtil;
import com.jmu.edu.IMApplication.utils.ViewUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class ReviseCustomTextFragment extends Fragment {
    private static final String TAG = "reviseCustomText";
    private RecyclerView recyclerView;
    private MaterialButton addButton, backButton;
    private TextView titleText;
    private GestureAndFaceResult result;
    private ReviseCustomTextItemAdapter adapter;
    private EditDialog editDialog;

    public void setResult(GestureAndFaceResult result) {
        this.result = result;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_revise_custom_text, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        recyclerView = getView().findViewById(R.id.fragment_revise_custom_text_recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        addButton = getView().findViewById(R.id.fragment_revise_custom_text_add);
        backButton = getView().findViewById(R.id.fragment_revise_custom_text_back);
        titleText = getView().findViewById(R.id.fragment_revise_custom_text_title);
        initListener();
        initData();
    }

    private void initData() {
        titleText.setText(result.getIdentify().getChineseName());
        if (adapter == null) {
            adapter = new ReviseCustomTextItemAdapter();
        }
        adapter.setResult(result);
        if (recyclerView.getAdapter() == null) {
            recyclerView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        ViewUtils.addBackListenerForHide(getView(), backButton);

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {

        } else {
            initData();
        }
    }

    private void initListener() {
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editDialog == null) {
                    createEditDialog();
                } else {
                    showEditDialog();
                }
            }
        });
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.hideFragment(ReviseCustomTextFragment.this, R.anim.from_right, R.anim.out_right);
            }
        });
    }


    private void createEditDialog() {
        editDialog = new EditDialog(getContext(), 0);
        editDialog.setTitle("设置文本");
        editDialog.setOnConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newText = editDialog.getInputText();
                if (!newText.isEmpty()) {
                    // map将作为参数进行数据库更新
                    Map<String, String> map = new HashMap<>();
                    map.put("username", MyApplication.getUser().getUserName());
                    map.put("chineseName", result.getIdentify().getChineseName());
                    map.put("identifyText", newText);
                    //添加到数据库
                    insertUserIdentify(map);
                    // 这个userIdentify纯粹是用来展示用的
                    UserIdentify userIdentify = new UserIdentify();
                    userIdentify.setIdentifyText(newText);
                    result.getUserIdentifyList().add(userIdentify);
                    adapter.notifyItemInserted(result.getUserIdentifyList().size());
                }
                editDialog.dismiss();
            }
        });
        editDialog.setCancelable(true);
        editDialog.show();
    }

    private void insertUserIdentify(Map<String, String> map) {
        RequestBody requestBody = RequestBody.create(HttpUtil.JSON, new Gson().toJson(map));
        Request request = new Request.Builder().post(requestBody).url(HttpUtil.URL_ADD_USER_IDENTIFY).build();
        MyApplication.getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: ", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse: " + response.body().string());
            }
        });
    }

    private void showEditDialog() {
        editDialog.show();
    }
}